package com.taxshare.purchaser.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.taxshare.minio.utils.MinIOUtils;
import com.taxshare.purchaser.constant.CodeConstant;
import com.taxshare.purchaser.entity.*;
import com.taxshare.purchaser.entity.model.InvoiceDetailModel;
import com.taxshare.purchaser.entity.model.InvoiceMainInfoModel;
import com.taxshare.purchaser.mapper.*;
import com.taxshare.purchaser.remote.ApiClientService;
import com.taxshare.purchaser.remote.ManagerClientService;
import com.taxshare.purchaser.util.InvoiceCheckUtil;
import com.taxshare.purchaser.util.TransformationUtil;
import com.taxshare.purchaser.view.dto.CheckInvoiceDTO;
import com.taxshare.purchaser.view.dto.HandEnterDTO;
import com.taxshare.purchaser.view.dto.ImageUploadInvoiceDTO;
import com.taxshare.purchaser.view.dto.InterfaceInvoiceDTO;
import com.taxshare.purchaser.view.vo.*;
import com.taxshare.response.beans.Response;
import com.taxshare.tools.constant.CommonConstant;
import com.taxshare.tools.token.UserInfoUtil;
import com.taxshare.tools.util.Base64Util;
import com.taxshare.tools.util.BeanSelfUtils;
import com.taxshare.tools.util.UUIDUitl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import static com.taxshare.purchaser.constant.MinIOConstant.BUCKET_NAME;
import static com.taxshare.purchaser.constant.MinIOConstant.GROUP_INVOICE;

/**
 * @ClassName: InvoiceCollectService
 * @Description: 发票采集（他方调用）
 * @author: hjh
 * @date: 2021/5/24 15:39
 */
@Slf4j
@Service
public class InvoiceCollectService extends ServiceImpl<InvoiceCollectionMapper, InvoiceCollectionEntity> {

    @Autowired
    CheckLogMapper checkLogMapper;

    @Autowired
    InvoiceDetailService invoiceDetailService;

    @Autowired
    InvoicePoolService invoicePoolService;

    @Autowired
    ApiClientService apiClientService;

    @Autowired
    InvoiceReviewRulesMapper ReviewRulesMapper;

    @Autowired
    InvoiceReviewRulesService reviewRulesService;

    @Autowired
    MinIOUtils minIOUtils;

    @Autowired
    InvoicePoolMapper invoicePoolMapper;

    @Autowired
    TrainTicketPoolMapper trainTicketPoolMapper;

    @Autowired
    BusTicketPoolMapper busTicketPoolMapper;

    @Autowired
    MachinTicketPoolMapper machinTicketPoolMapper;

    @Autowired
    TaxiTicketPoolMapper taxiTicketPoolMapper;

    @Autowired
    TollTicketPoolMapper tollTicketPoolMapper;

    @Autowired
    QuotaTicketPoolMapper quotaTicketPoolMapper;

    @Autowired
    PlaneTicketPoolMapper planeTicketPoolMapper;

    @Autowired
    PlaneTicketDetailMapper planeTicketDetailMapper;

    @Autowired
    PlaneTicketDetailService planeTicketDetailService;

    @Autowired
    ManagerClientService managerClientService;

    private static final String timeStart = " 00:00:00";
    private static final String timeEnd = " 23:59:59";

    /***
     * OCR识别
     * @param imageUploadInvoiceDTO
     * @return
     */
    public Response uploadInvoiceImage(ImageUploadInvoiceDTO imageUploadInvoiceDTO) {
        Response response = apiClientService.invoiceDiscern(imageUploadInvoiceDTO);
        PurchaserApiRespVO purchaserApiRespVO = JSONObject.parseObject(JSONObject.toJSONString(response.getData()), PurchaserApiRespVO.class);
        Response res = new Response<>();
        if (CommonConstant.INTERFACE_SUCCESS.equals(purchaserApiRespVO.getCode())) {
            dealInovoiceData(purchaserApiRespVO);
            res.setCode(CommonConstant.SUCCESS);
        } else {
            res.setCode(purchaserApiRespVO.getCode());
        }
        res.setData(purchaserApiRespVO.getContent());
        res.setMsg(purchaserApiRespVO.getMsg());
        return res;
    }

    /**
     * ORC查验接口（返回全票数据）
     *
     * @param handEnterDTO
     * @return
     */
    public Response checkInvoiceSync(HandEnterDTO handEnterDTO) {
        CheckInvoiceDTO checkInvoiceDTO = new CheckInvoiceDTO();
        BeanUtil.copyProperties(handEnterDTO, checkInvoiceDTO);
        return checkInvoice(checkInvoiceDTO);
    }

    /**
     * 组装数据，同步远程调用查验接口
     *
     * @param checkInvoiceDTO
     * @return
     */
    private Response checkInvoice(CheckInvoiceDTO checkInvoiceDTO) {
        String userID = UserInfoUtil.getUserID();
        checkInvoiceDTO.setInvoiceType(TransformationUtil.transInvoiceType(checkInvoiceDTO.getInvoiceType()));
        CheckLogEntity checkLogEntity = new CheckLogEntity();
        CheckLogChangeVO checkLogChangeVO = new CheckLogChangeVO();
        InvoicePoolEntity invoicePoolEntity = new InvoicePoolEntity();
        InvoiceCollectOcrVO invoiceCollectOCRVO = new InvoiceCollectOcrVO();
        InvoiceDetailOcrVO invoiceDetailOCRVO = new InvoiceDetailOcrVO();
        //入采集表
        InvoicePoolEntity invoicePool = collectionInvoice(checkInvoiceDTO, invoicePoolEntity);
        try {
            Response response = apiClientService.invoiceCheck(checkInvoiceDTO);
            //T0000接口调用成功
            if (CodeConstant.T0000.equals(response.getCode())) {
                Map resMap = (Map) response.getData();
                PurchaserApiRespVO checkRespVO = BeanUtil.mapToBean((Map<?, ?>) resMap, PurchaserApiRespVO.class, false);
                String checkMsg = checkRespVO.getMsg();
                //查验成功，处理查验返回数据
                if (CodeConstant.SUCCESS.equals(checkRespVO.getCode())) {
                    Map<String, Object> checkMap = InvoiceCheckUtil.assembly(checkRespVO.getContent());
                    InvoiceMainInfoModel mainInfoModel = (InvoiceMainInfoModel) checkMap.get("invoiceMainInfo");
                    mainInfoModel.setKprq(getFormatDate(mainInfoModel.getKprq()));
                    List<InvoiceDetailModel> detailModelList = (List<InvoiceDetailModel>) checkMap.get("invoiceDetailInfo");
                    //插入发票查验日志
                    BeanSelfUtils.copyBean(mainInfoModel, checkLogChangeVO);
                    BeanUtil.copyProperties(checkLogChangeVO, checkLogEntity);
                    checkLogEntity.setCreateUserid(userID);
                    checkLogEntity.setCheckStatus(CodeConstant.CHECK_SUCCESS);
                    checkLogEntity.setCheckResult(checkMsg);
                    checkLogEntity.setUuid(UUIDUitl.UUID32(false));
                    //补全采集发票数据
                    BeanUtil.copyProperties(checkLogEntity, invoicePoolEntity);
                    invoicePoolEntity.setCheckStatus(CodeConstant.CHECK_SUCCESS);
                    invoicePoolEntity.setCheckResult(checkMsg);
                    if (StrUtil.isNotBlank(invoicePoolEntity.getInvoiceStatus())) {
                        invoicePoolEntity.setInvoiceStatus(InvoiceCheckUtil.transInvoiceStatus(invoicePool.getInvoiceStatus()));
                    }
                    //处理返回明细信息且入明细表
                    try {
                        ArrayList<InvoiceDetailEntity> detailList = new ArrayList<>();
                        for (InvoiceDetailModel invoiceDetailModel : detailModelList) {
                            InvoiceDetailChangeVO invoiceDetailChangeVO = new InvoiceDetailChangeVO();
                            InvoiceDetailEntity invoiceDetailEntity = new InvoiceDetailEntity();
                            BeanSelfUtils.copyBean(invoiceDetailModel, invoiceDetailChangeVO);
                            BeanUtil.copyProperties(invoiceDetailChangeVO, invoiceDetailEntity);
                            invoiceDetailEntity.setInvoiceCode(invoicePool.getInvoiceCode());
                            invoiceDetailEntity.setInvoiceNo(invoicePool.getInvoiceNo());
                            invoiceDetailEntity.setUuid(UUIDUitl.UUID32(false));
                            if (StrUtil.isBlank(invoiceDetailEntity.getModel())) {
                                invoiceDetailEntity.setModel("");
                            }
                            if (StrUtil.isBlank(invoiceDetailEntity.getUnit())) {
                                invoiceDetailEntity.setUnit("");
                            }
                            if (StrUtil.isBlank(invoiceDetailEntity.getGoodsNumber())) {
                                invoiceDetailEntity.setGoodsNumber("");
                            }
                            detailList.add(invoiceDetailEntity);
                            //返回invoiceCollectOCRVo（处理明细信息）
                            BeanUtil.copyProperties(invoiceDetailEntity, invoiceDetailOCRVO);
                            invoiceCollectOCRVO.getInvoiceDetailOcrVOS().add(invoiceDetailOCRVO);
                        }
                        QueryWrapper<InvoiceDetailEntity> queryWrapper = new QueryWrapper<>();
                        queryWrapper.eq("invoice_code", invoicePool.getInvoiceCode())
                                .eq("invoice_no", invoicePool.getInvoiceNo());
                        List<InvoiceDetailEntity> list = invoiceDetailService.list(queryWrapper);
                        if (list != null && !list.isEmpty()) {
                            invoiceDetailService.remove(queryWrapper);
                        }
                        invoiceDetailService.saveBatch(detailList);
                        InvoiceCollectionEntity entity = null;
                        InvoiceCollectionEntity entity1 = new InvoiceCollectionEntity();
                        try {
                            //发票审核规则
                            entity1.setPurchaserTaxNo(invoicePoolEntity.getPurchaserTaxNo());
                            entity1.setPurchaserName(invoicePoolEntity.getPurchaserName());
                            entity1.setSellerTaxNo(invoicePoolEntity.getSellerTaxNo());
                            entity1.setInvoiceType(invoicePoolEntity.getInvoiceType());
                            entity1.setSellerName(invoicePoolEntity.getSellerName());
                            entity1.setSellerTaxNo(invoicePoolEntity.getSellerTaxNo());
                            entity1.setInvoiceCode(invoicePoolEntity.getInvoiceCode());
                            entity1.setInvoiceNo(invoicePoolEntity.getInvoiceNo());
                            entity = checkInvoiceRules(entity1);
                        } catch (Exception e) {
                            log.info("发票审核流程异常：{}", e);
                        }
                        checkLogEntity.setRulesStatus(entity.getRulesStatus());
                        checkLogMapper.insert(checkLogEntity);
                        if (CodeConstant.RULES_SUCCESS.equals(entity.getRulesStatus())) {
                            invoiceCollectOCRVO.getCheckReviewResultVO().setReviewCode(entity.getRulesStatus());
                            invoiceCollectOCRVO.getCheckReviewResultVO().setReviewResult(entity.getRulesResult());
                            invoiceCollectOCRVO.getCheckReviewResultVO().setCheckCode(invoicePoolEntity.getCheckStatus());
                            invoiceCollectOCRVO.getCheckReviewResultVO().setCheckResult(invoicePoolEntity.getCheckResult());
                            //返回invoiceCollectOCRVo（全票面信息）
                        }
                        BeanUtil.copyProperties(invoicePoolEntity, invoiceCollectOCRVO.getInvoiceCollectionVO());
                        //更新采集表
                        UpdateWrapper<InvoicePoolEntity> updateWrapper = new UpdateWrapper<>();
                        updateWrapper.eq("invoice_code", invoicePool.getInvoiceCode());
                        updateWrapper.eq("invoice_no", invoicePool.getInvoiceNo());
                        invoicePoolMapper.update(invoicePoolEntity, updateWrapper);
                    } catch (Exception e) {
                        log.info("发票明细处理有误：{}", e);
                    }
                } else {
                    invoicePool.setCheckStatus(CodeConstant.CHECK_FAIL);
                    invoicePool.setCheckResult(response.getMsg());
                    invoicePoolService.updateById(invoicePool);
                    updateFailLogAndCollectionInfo(checkMsg, userID, checkInvoiceDTO);
                    return Response.error(CodeConstant.ERROR, checkMsg);
                }
            } else {
                invoicePool.setCheckStatus(CodeConstant.CHECK_FAIL);
                invoicePool.setCheckResult(response.getMsg());
                invoicePoolService.updateById(invoicePool);
                updateFailLogAndCollectionInfo("发票远程查验接口调用失败", userID, checkInvoiceDTO);
                return Response.error("PUR_ERROR_001");
            }
        } catch (Exception e) {
            log.error("查验接口异常：{}", e);
            invoicePool.setCheckStatus(CodeConstant.CHECK_FAIL);
            invoicePool.setCheckResult("查验接口异常内部异常，请稍后再试……");
            invoicePoolService.updateById(invoicePool);
            updateFailLogAndCollectionInfo("发票查验异常", userID, checkInvoiceDTO);
            return Response.error("PUR_ERROR_002");
        }
        return Response.success(invoiceCollectOCRVO);
    }

    /**
     * 入发票池表
     */
    private InvoicePoolEntity collectionInvoice(CheckInvoiceDTO checkInvoiceDTO, InvoicePoolEntity invoicePoolEntity) {
        QueryWrapper<InvoicePoolEntity> invoiceQuery = new QueryWrapper<>();
        invoiceQuery.eq("invoice_code", checkInvoiceDTO.getInvoiceCode());
        invoiceQuery.eq("invoice_no", checkInvoiceDTO.getInvoiceNo());
        InvoicePoolEntity invoiceCollection = invoicePoolMapper.selectOne(invoiceQuery);
        invoicePoolEntity.setInvoiceCode(checkInvoiceDTO.getInvoiceCode());
        invoicePoolEntity.setCollectMark(CodeConstant.COMM_CODE_1);
        invoicePoolEntity.setInvoiceNo(checkInvoiceDTO.getInvoiceNo());
        invoicePoolEntity.setInvoiceDate(checkInvoiceDTO.getInvoiceDate());
        invoicePoolEntity.setCheckCode(checkInvoiceDTO.getCheckCode());
        invoicePoolEntity.setInvoiceType(checkInvoiceDTO.getInvoiceType());
        if (invoiceCollection != null) {
            BeanUtil.copyProperties(invoicePoolEntity, invoiceCollection);
            invoicePoolMapper.updateById(invoiceCollection);
            return invoiceCollection;
        } else {
            invoicePoolEntity.setUuid(UUIDUitl.UUID32());
            invoicePoolService.save(invoicePoolEntity);
            return invoicePoolEntity;
        }
    }

    /**
     * 插入查验失败日志和发票信息
     *
     * @param checkMsg 查验失败信息
     * @param userId   查验人id
     */
    private void updateFailLogAndCollectionInfo(String checkMsg, String userId, CheckInvoiceDTO checkInvoiceDTO) {
        CheckLogEntity checkLogEntity = new CheckLogEntity();
        String uuid = UUIDUitl.UUID32(false);
        checkLogEntity.setUuid(uuid);
        checkLogEntity.setCreateUserid(userId);
        checkLogEntity.setCheckResult(checkMsg);
        checkLogEntity.setCheckStatus(CodeConstant.CHECK_FAIL);
        checkLogEntity.setInvoiceNo(checkInvoiceDTO.getInvoiceNo());
        checkLogEntity.setInvoiceCode(checkInvoiceDTO.getInvoiceCode());
        checkLogEntity.setInvoiceType(checkInvoiceDTO.getInvoiceType());
        if (StrUtil.isNotBlank(checkInvoiceDTO.getAmountWithOutTax())) {
            checkLogEntity.setAmountWithOutTax(checkInvoiceDTO.getAmountWithOutTax());
        }
        if (StrUtil.isNotBlank(checkInvoiceDTO.getCheckCode())) {
            checkLogEntity.setCheckCode(checkInvoiceDTO.getCheckCode());
        }
        checkLogMapper.insert(checkLogEntity);
    }

    /**
     * 处理发票查验返回的日期格式
     *
     * @param dateStr
     * @return
     */
    private String getFormatDate(String dateStr) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd");
        try {
            Date date = sdf.parse(dateStr);
            return sdf2.format(date);
        } catch (ParseException e) {
            log.error("日期格式异常：{}", e);
        }
        return dateStr;
    }

    /**
     * 发票审核规则
     *
     * @param invoiceCollectionEntity
     */
    private InvoiceCollectionEntity checkInvoiceRules(InvoiceCollectionEntity invoiceCollectionEntity) {
        //校验发票规则
        InvoiceReviewRulesEntity entitySH = ReviewRulesMapper.selectOne(new QueryWrapper<InvoiceReviewRulesEntity>().eq("tax_number", invoiceCollectionEntity.getPurchaserTaxNo()));
        if (entitySH != null) {
            return reviewRulesService.rulesReview(invoiceCollectionEntity, entitySH.getUuid());
        }
        if (entitySH == null) {
            InvoiceReviewRulesEntity entityJT = ReviewRulesMapper.selectOne(new QueryWrapper<InvoiceReviewRulesEntity>().eq("scope_application", "1"));
            return reviewRulesService.rulesReview(invoiceCollectionEntity, entityJT.getUuid());
        }
        return null;
    }

    public Response dealInovoiceData(PurchaserApiRespVO purchaserApiRespVO) {
        String invoiceInfo = Base64Util.decode(purchaserApiRespVO.getContent());
        JSONArray invoiceList = JSONUtil.parseArray(invoiceInfo);
        int invoiceNumber = invoiceList.size();
        for (int i = 0; i < invoiceNumber; i++) {
            cn.hutool.json.JSONObject invoiceData = invoiceList.getJSONObject(i);
            String invoiceType = invoiceData.getStr("invoice_type");
            Response message = new Response();
            if (CodeConstant.OCRINVOICE_LIST.contains(invoiceType)) {
                //处理增值税发票数据
                message = dealInvoiceData(invoiceData);
            } else {
                //处理非增值税发票数据
                message = dealOtherInvoice(invoiceData);
            }
            if ("PUR_102".equals(message.getCode())) {
                return Response.error("PUR_102");
            }
        }
        return Response.success();
    }

    //处理非增值税发票数据
    private Response dealOtherInvoice(cn.hutool.json.JSONObject invoiceData) {
        String invoiceType = invoiceData.getStr("invoice_type");
        Response message = new Response();
        if (CodeConstant.INVOICETYPE_HCP.equals(invoiceType)) {
            //火车票【10503】
            message = dealTrainTicket(invoiceData);
        } else if (CodeConstant.INVOICETYPE_CZP.equals(invoiceType)) {
            //出租车发票【10500】
            message = dealTaxiTicket(invoiceData);
        } else if (CodeConstant.INVOICETYPE_DEFP.equals(invoiceType)) {
            //定额发票【10200】
            message = dealQuotaTicket(invoiceData);
        } else if (CodeConstant.INVOICETYPE_FJP.equals(invoiceType)) {
            //航空运输电子客票行程单【10506】
            message = dealPlaneTicket(invoiceData);
        } else if (CodeConstant.INVOICETYPE_GLFP.equals(invoiceType)) {
            //过路费发票【10507】
            message = dealTollTicket(invoiceData);
        } else if (CodeConstant.INVOICETYPE_JDFP.equals(invoiceType)) {
            //机打发票【10400】
            message = dealMachinTicket(invoiceData);
        } else if (CodeConstant.INVOICETYPE_QCP.equals(invoiceType)) {
            //客运汽车【10505】
            message = dealBusTicket(invoiceData);
        }
        return message;
    }


    //处理增值税发票数据
    private Response dealInvoiceData(cn.hutool.json.JSONObject invoiceData) {
        String uuid = UUIDUitl.UUID32(false);
        CheckInvoiceDTO checkInvoiceDTO = new CheckInvoiceDTO();
        checkInvoiceDTO.setInvoiceType(BeanSelfUtils.convertInvoiceType(invoiceData.getStr("invoice_type")));
        checkInvoiceDTO.setInvoiceCode(invoiceData.getStr("invoice_code1"));
        checkInvoiceDTO.setInvoiceNo(invoiceData.getStr("invoice_no1"));
        if(StrUtil.isBlank(invoiceData.getStr("create_date"))){
            checkInvoiceDTO.setInvoiceDate("");
        } else {
            checkInvoiceDTO.setInvoiceDate((BeanSelfUtils.removerStr(invoiceData.getStr("create_date"))));
        }
        checkInvoiceDTO.setAmountWithOutTax(invoiceData.getStr("total"));
        //取校验码后6位
        if (StrUtil.isNotBlank(invoiceData.getStr("check_code")) && invoiceData.getStr("check_code").length() >= 6) {
            checkInvoiceDTO.setCheckCode(invoiceData.getStr("check_code").substring(invoiceData.getStr("check_code").length() - 6));
        } else {
            checkInvoiceDTO.setCheckCode(invoiceData.getStr("check_code"));
        }
        checkInvoiceDTO.setUuid(uuid);
        //记录查验日志
        CheckLogEntity checkLogEntity = new CheckLogEntity();
        BeanUtil.copyProperties(checkInvoiceDTO, checkLogEntity);
        checkLogEntity.setUuid(UUIDUitl.UUID32(false));
        checkLogEntity.setLinkId(uuid);
        checkLogMapper.insert(checkLogEntity);
        //校验去重
        QueryWrapper<InvoicePoolEntity> invoiceQuery = new QueryWrapper<>();
        String invoiceCode = invoiceData.getStr("invoice_code1");
        String invoiceNo = invoiceData.getStr("invoice_no1");
        invoiceQuery.eq("invoice_code", invoiceCode);
        invoiceQuery.eq("invoice_no", invoiceNo);
        InvoicePoolEntity invoicePoolEntity = invoicePoolMapper.selectOne(invoiceQuery);
        if (invoicePoolEntity != null) {
            return Response.error("PUR_102");
        }
        InvoicePoolEntity invoicePool = new InvoicePoolEntity();
        BeanUtil.copyProperties(checkInvoiceDTO, invoicePool);
        invoicePool.setReimbursementStatus(CodeConstant.REIMBURSEMENT_1);
        invoicePool.setPersonLiable(UserInfoUtil.getUserNickName());
        invoicePool.setPersonLiableId(UserInfoUtil.getUserID());
//        invoicePool.setProcedureStatus(CodeConstant.APPROVAL_1);
        invoicePool.setCheckStatus(CodeConstant.NOT_CHECK);
        invoicePool.setRulesStatus(CodeConstant.NOT_RULES);
        invoicePool.setCheckNumber(0);
        invoicePool.setUuid(uuid);
        invoicePool.setDataSource(CodeConstant.UPLOAD_1);
        invoicePool.setSubmitStatus(CodeConstant.SUBMIT_STATUS_0);
//        invoiceCollectionEntity.setImageId(imageId);
        invoicePool.setCreateTimeStr(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        invoicePool.setCollector(UserInfoUtil.getUserNickName());
        invoicePool.setCollectorId(UserInfoUtil.getUserID());
        invoicePool.setCollectMark(CodeConstant.COMM_CODE_0);
        invoicePoolMapper.insert(invoicePool);
        return Response.success();
    }

    //火车票解析入库【10503】
    private Response dealTrainTicket(cn.hutool.json.JSONObject invoiceData) {
        //火车票只有发票号码，没有发票代码，用乘车人姓名+发票号确定唯一
        String invoiceNo = invoiceData.getStr("invoice_no1");
        String travelName = invoiceData.getStr("name");
        QueryWrapper<TrainTicketPoolEntity> trainQuery = new QueryWrapper<>();
        trainQuery.eq("invoice_no", invoiceNo);
        trainQuery.eq("travel_name", travelName);
        TrainTicketPoolEntity trainTicket = trainTicketPoolMapper.selectOne(trainQuery);
        TrainTicketPoolEntity trainTicketEntity = new TrainTicketPoolEntity();
        trainTicketEntity.setUuid(UUIDUitl.UUID32(false));
        trainTicketEntity.setInvoiceType(BeanSelfUtils.convertInvoiceType(invoiceData.getStr("invoice_type")));
        trainTicketEntity.setConsumeKind(invoiceData.getStr("kind"));
        trainTicketEntity.setInvoiceNo(invoiceNo);
        String travelDate = invoiceData.getStr("create_date");
        if (StrUtil.isNotBlank(travelDate)) {
            trainTicketEntity.setTravelDate(BeanSelfUtils.removerStr(travelDate));
        }
        trainTicketEntity.setTravelTime(invoiceData.getStr("time"));
        trainTicketEntity.setTravelName(travelName);
        trainTicketEntity.setFromStation(invoiceData.getStr("station_geton"));
        trainTicketEntity.setArriveStation(invoiceData.getStr("station_getoff"));
        trainTicketEntity.setTrainNumber(invoiceData.getStr("train_number"));
        trainTicketEntity.setSeatGrade(invoiceData.getStr("seat"));
        trainTicketEntity.setAmountBig(invoiceData.getStr("amount_big"));
        trainTicketEntity.setAmountSmall(invoiceData.getStr("amount_small"));
        trainTicketEntity.setSerialNumber(invoiceData.getStr("serial_number"));
        trainTicketEntity.setIdNumber(invoiceData.getStr("user_id"));
//        trainTicketEntity.setImageId(imageId);
        trainTicketEntity.setCollector(UserInfoUtil.getUserNickName());
        trainTicketEntity.setCollectorId(UserInfoUtil.getUserID());
        trainTicketEntity.setPersonLiable(UserInfoUtil.getUserNickName());
        trainTicketEntity.setPersonLiableId(UserInfoUtil.getUserID());
        trainTicketEntity.setReimbursementStatus(CodeConstant.REIMBURSEMENT_1);
//        trainTicketEntity.setProcedureStatus(CodeConstant.APPROVAL_1);
        trainTicketEntity.setCreateTimeStr(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        if (trainTicket != null) {
//            minIOUtils.removeObject(BUCKET_NAME, GROUP_INVOICE, trainTicket.getImageId());
//            trainTicketPoolMapper.deleteById(trainTicket.getUuid());
//            trainTicketPoolMapper.insert(trainTicketEntity);
            return Response.error("PUR_102");
        } else {
            trainTicketPoolMapper.insert(trainTicketEntity);
        }
        return Response.success();
    }

    //出租车票解析入库【10500】
    private Response dealTaxiTicket(cn.hutool.json.JSONObject invoiceData) {
        //用发票代码+发票号码确定唯一
        QueryWrapper<TaxiTicketPoolEntity> taxiQuery = new QueryWrapper<>();
        String invoiceCode = invoiceData.getStr("invoice_code1");
        String invoiceNo = invoiceData.getStr("invoice_no1");
        taxiQuery.eq("invoice_code", invoiceCode);
        taxiQuery.eq("invoice_no", invoiceNo);
        TaxiTicketPoolEntity taxiTicket = taxiTicketPoolMapper.selectOne(taxiQuery);
        TaxiTicketPoolEntity taxiTicketEntity = new TaxiTicketPoolEntity();
        taxiTicketEntity.setUuid(UUIDUitl.UUID32(false));
        taxiTicketEntity.setInvoiceType(BeanSelfUtils.convertInvoiceType(invoiceData.getStr("invoice_type")));
        taxiTicketEntity.setConsumeKind(invoiceData.getStr("kind"));
        taxiTicketEntity.setInvoiceCode(invoiceCode);
        taxiTicketEntity.setInvoiceNo(invoiceNo);
        String createDate = invoiceData.getStr("create_date");
        if (StrUtil.isNotBlank(createDate)) {
            taxiTicketEntity.setCreateDate(BeanSelfUtils.removerStr(createDate));
        }
        taxiTicketEntity.setInvoicePlace(invoiceData.getStr("place"));
        taxiTicketEntity.setTimeGeton(invoiceData.getStr("time_geton"));
        taxiTicketEntity.setTimeGetoff(invoiceData.getStr("time_getoff"));
        taxiTicketEntity.setMileage(invoiceData.getStr("mileage"));
        taxiTicketEntity.setAmountBig(invoiceData.getStr("amount_big"));
        taxiTicketEntity.setAmountSmall(invoiceData.getStr("amount_small"));
        taxiTicketEntity.setFare(invoiceData.getStr("fare"));
        taxiTicketEntity.setSurcharge(invoiceData.getStr("surcharge"));
//        taxiTicketEntity.setImageId(imageId);
        taxiTicketEntity.setCollector(UserInfoUtil.getUserNickName());
        taxiTicketEntity.setCollectorId(UserInfoUtil.getUserID());
        taxiTicketEntity.setPersonLiable(UserInfoUtil.getUserNickName());
        taxiTicketEntity.setPersonLiableId(UserInfoUtil.getUserID());
        taxiTicketEntity.setReimbursementStatus(CodeConstant.REIMBURSEMENT_1);
//        taxiTicketEntity.setProcedureStatus(CodeConstant.APPROVAL_1);
        taxiTicketEntity.setCreateTimeStr(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        if (taxiTicket != null) {
//                minIOUtils.removeObject(BUCKET_NAME, GROUP_INVOICE, taxiTicket.getImageId());
//            taxiTicketPoolMapper.deleteById(taxiTicket.getUuid());
//            taxiTicketPoolMapper.insert(taxiTicketEntity);
            return Response.error("PUR_102");
        } else {
            taxiTicketPoolMapper.insert(taxiTicketEntity);
        }
        return Response.success();
    }

    //定额票解析入库【10200】
    private Response dealQuotaTicket(cn.hutool.json.JSONObject invoiceData) {
        //用发票代码+发票号码确定唯一
        String invoiceCode = invoiceData.getStr("invoice_code1");
        String invoiceNo = invoiceData.getStr("invoice_no1");
        QueryWrapper<QuotaTicketPoolEntity> quotaQuery = new QueryWrapper<>();
        quotaQuery.eq("invoice_code", invoiceCode);
        quotaQuery.eq("invoice_no", invoiceNo);
        QuotaTicketPoolEntity quotaTicket = quotaTicketPoolMapper.selectOne(quotaQuery);
        QuotaTicketPoolEntity quotaTicketEntity = new QuotaTicketPoolEntity();
        quotaTicketEntity.setUuid(UUIDUitl.UUID32(false));
        quotaTicketEntity.setInvoiceType(BeanSelfUtils.convertInvoiceType(invoiceData.getStr("invoice_type")));
        quotaTicketEntity.setConsumeKind(invoiceData.getStr("kind"));
        quotaTicketEntity.setInvoiceCode(invoiceCode);
        quotaTicketEntity.setInvoiceNo(invoiceNo);
        quotaTicketEntity.setAmountBig(invoiceData.getStr("amount_big"));
        quotaTicketEntity.setAmountSmall(invoiceData.getStr("amount_small"));
//        quotaTicketEntity.setImageId(imageId);
        quotaTicketEntity.setCollector(UserInfoUtil.getUserNickName());
        quotaTicketEntity.setCollectorId(UserInfoUtil.getUserID());
        quotaTicketEntity.setPersonLiable(UserInfoUtil.getUserNickName());
        quotaTicketEntity.setPersonLiableId(UserInfoUtil.getUserID());
        quotaTicketEntity.setReimbursementStatus(CodeConstant.REIMBURSEMENT_1);
//        quotaTicketEntity.setProcedureStatus(CodeConstant.APPROVAL_1);
        quotaTicketEntity.setCreateTimeStr(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        if (quotaTicket != null) {
//            minIOUtils.removeObject(BUCKET_NAME, GROUP_INVOICE, quotaTicket.getImageId());
//            quotaTicketPoolMapper.deleteById(quotaTicket.getUuid());
//            quotaTicketPoolMapper.insert(quotaTicketEntity);
            return Response.error("PUR_102");
        } else {
            quotaTicketPoolMapper.insert(quotaTicketEntity);
        }
        return Response.success();
    }

    //航空运输电子客票行程单解析入库【10506】
    private Response dealPlaneTicket(cn.hutool.json.JSONObject invoiceData) {
        //机票没有发票代码，用电子客票号码+乘机人姓名确定唯一
        String invoiceNo = invoiceData.getStr("invoice_no1");
        String userName = invoiceData.getStr("user_name");
        QueryWrapper<PlaneTicketPoolEntity> planeQuery = new QueryWrapper<>();
        planeQuery.eq("ticket_no", invoiceNo);
        planeQuery.eq("user_name", userName);
        PlaneTicketPoolEntity planeTicket = planeTicketPoolMapper.selectOne(planeQuery);
        PlaneTicketPoolEntity planeTicketEntity = new PlaneTicketPoolEntity();
        String uuid = UUIDUitl.UUID32(false);
        planeTicketEntity.setUuid(uuid);
        planeTicketEntity.setInvoiceType(BeanSelfUtils.convertInvoiceType(invoiceData.getStr("invoice_type")));
        planeTicketEntity.setConsumeKind(invoiceData.getStr("kind"));
        planeTicketEntity.setUserName(userName);
        planeTicketEntity.setIdNumber(invoiceData.getStr("user_id"));
        planeTicketEntity.setTicketNo(invoiceNo);
        planeTicketEntity.setCheckCode(invoiceData.getStr("check_code"));
        String ticketDate = invoiceData.getStr("create_date");
        if (StrUtil.isNotBlank(ticketDate)) {
            planeTicketEntity.setTicketDate(BeanSelfUtils.removerStr(ticketDate));
        }
        planeTicketEntity.setAgentCode(invoiceData.getStr("agentcode"));
        planeTicketEntity.setIssueBy(invoiceData.getStr("issue_by"));
        planeTicketEntity.setTicketPrice(invoiceData.getStr("fare"));
        planeTicketEntity.setTotalTax(invoiceData.getStr("total_tax"));
        planeTicketEntity.setFuelSurcharge(invoiceData.getStr("fuel_surcharge"));
        planeTicketEntity.setCaacDevelopmentFund(invoiceData.getStr("caac_development_fund"));
        planeTicketEntity.setInsurance(invoiceData.getStr("insurance"));
        planeTicketEntity.setInternationalFlag(invoiceData.getStr("international_flag"));
        planeTicketEntity.setPrintSerialNumber(invoiceData.getStr("print_serial_number"));
        planeTicketEntity.setAmountBig(invoiceData.getStr("amount_big"));
        planeTicketEntity.setAmountSmall(invoiceData.getStr("amount_small"));
//        planeTicketEntity.setImageId(imageId);
        planeTicketEntity.setCollector(UserInfoUtil.getUserNickName());
        planeTicketEntity.setCollectorId(UserInfoUtil.getUserID());
        planeTicketEntity.setPersonLiable(UserInfoUtil.getUserNickName());
        planeTicketEntity.setPersonLiableId(UserInfoUtil.getUserID());
        planeTicketEntity.setReimbursementStatus(CodeConstant.REIMBURSEMENT_1);
//        planeTicketEntity.setProcedureStatus(CodeConstant.APPROVAL_1);
        planeTicketEntity.setCreateTimeStr(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        if (planeTicket != null) {
//            minIOUtils.removeObject(BUCKET_NAME, GROUP_INVOICE, planeTicket.getImageId());
//            planeTicketPoolMapper.deleteById(planeTicket.getUuid());
//            planeTicketPoolMapper.insert(planeTicketEntity);
//            dealPlaneTicketDetail(invoiceData, planeTicket.getUuid(), uuid);
            return Response.error("PUR_102");
        } else {
            planeTicketPoolMapper.insert(planeTicketEntity);
            dealPlaneTicketDetail(invoiceData, "", uuid);
        }
        return Response.success();
    }

    //处理航空运输电子客票行程单航班信息
    private void dealPlaneTicketDetail(cn.hutool.json.JSONObject invoiceData, String deleteUuid, String inserUuid) {
        List<PlaneTicketDetailEntity> planeTicketDetailEntities = new ArrayList<>();
        String flights = invoiceData.getStr("flights");
        JSONArray flightsInfo = JSONUtil.parseArray(flights);
        int infoSize = flightsInfo.size();
        for (int i = 0; i < infoSize; i++) {
            cn.hutool.json.JSONObject planeObject = flightsInfo.getJSONObject(i);
            PlaneTicketDetailEntity planeTicketDetailEntity = new PlaneTicketDetailEntity();
            planeTicketDetailEntity.setUuid(UUIDUitl.UUID32(false));
            planeTicketDetailEntity.setLinkId(inserUuid);
            planeTicketDetailEntity.setFromStation(planeObject.getStr("from"));
            planeTicketDetailEntity.setArriveStation(planeObject.getStr("to"));
            planeTicketDetailEntity.setFlightNumber(planeObject.getStr("flight_number"));
            String flightDate = planeObject.getStr("date");
            if (StrUtil.isNotBlank(flightDate)) {
                planeTicketDetailEntity.setFlightDate(BeanSelfUtils.removerStr(flightDate));
            }
            planeTicketDetailEntity.setFlightTime(planeObject.getStr("time"));
            planeTicketDetailEntity.setSeatGrade(planeObject.getStr("seat"));
            planeTicketDetailEntity.setCarrier(planeObject.getStr("carrier"));
            planeTicketDetailEntity.setClassName(planeObject.getStr("class_name"));
            planeTicketDetailEntity.setCreateTimeStr(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
            planeTicketDetailEntities.add(planeTicketDetailEntity);
        }
        planeTicketDetailMapper.delete(new QueryWrapper<PlaneTicketDetailEntity>().eq("link_id", deleteUuid));
        planeTicketDetailService.saveBatch(planeTicketDetailEntities);
    }

    //过路费发票解析入库【10507】
    private Response dealTollTicket(cn.hutool.json.JSONObject invoiceData) {
        //用发票代码+号码确定唯一
        String invoiceCode = invoiceData.getStr("invoice_code1");
        String invoiceNo = invoiceData.getStr("invoice_no1");
        QueryWrapper<TollTicketPoolEntity> tollQuery = new QueryWrapper<>();
        tollQuery.eq("invoice_code", invoiceCode);
        tollQuery.eq("invoice_no", invoiceNo);
        TollTicketPoolEntity tollTicket = tollTicketPoolMapper.selectOne(tollQuery);
        TollTicketPoolEntity tollTicketEntity = new TollTicketPoolEntity();
        tollTicketEntity.setUuid(UUIDUitl.UUID32(false));
        tollTicketEntity.setInvoiceType(BeanSelfUtils.convertInvoiceType(invoiceData.getStr("invoice_type")));
        tollTicketEntity.setConsumeKind(invoiceData.getStr("kind"));
        tollTicketEntity.setInvoiceCode(invoiceCode);
        tollTicketEntity.setInvoiceNo(invoiceNo);
        String travelDate = invoiceData.getStr("create_date");
        if (StrUtil.isNotBlank(travelDate)) {
            tollTicketEntity.setTravelDate(BeanSelfUtils.removerStr(travelDate));
        }
        tollTicketEntity.setTravelTime(invoiceData.getStr("time"));
        tollTicketEntity.setEntrance(invoiceData.getStr("entrance"));
        tollTicketEntity.setWayOut(invoiceData.getStr("exit"));
        tollTicketEntity.setAmountBig(invoiceData.getStr("amount_big"));
        tollTicketEntity.setAmountSmall(invoiceData.getStr("amount_small"));
//        tollTicketEntity.setImageId(imageId);
        tollTicketEntity.setCollector(UserInfoUtil.getUserNickName());
        tollTicketEntity.setCollectorId(UserInfoUtil.getUserID());
        tollTicketEntity.setPersonLiable(UserInfoUtil.getUserNickName());
        tollTicketEntity.setPersonLiableId(UserInfoUtil.getUserID());
        tollTicketEntity.setReimbursementStatus(CodeConstant.REIMBURSEMENT_1);
//        tollTicketEntity.setProcedureStatus(CodeConstant.APPROVAL_1);
        tollTicketEntity.setCreateTimeStr(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        if (tollTicket != null) {
//            minIOUtils.removeObject(BUCKET_NAME, GROUP_INVOICE, tollTicket.getImageId());
//            tollTicketPoolMapper.deleteById(tollTicket.getUuid());
//            tollTicketPoolMapper.insert(tollTicketEntity);
            return Response.error("PUR_102");
        } else {
            tollTicketPoolMapper.insert(tollTicketEntity);
        }
        return Response.success();
    }

    //机打发票解析入库【10400】
    private Response dealMachinTicket(cn.hutool.json.JSONObject invoiceData) {
        ////用发票代码+号码确定唯一
        String invoiceCode = invoiceData.getStr("invoice_code1");
        String invoiceNo = invoiceData.getStr("invoice_no1");
        QueryWrapper<MachinTicketPoolEntity> machinQuery = new QueryWrapper<>();
        machinQuery.eq("invoice_code", invoiceCode);
        machinQuery.eq("invoice_no", invoiceNo);
        MachinTicketPoolEntity machinTicket = machinTicketPoolMapper.selectOne(machinQuery);
        MachinTicketPoolEntity machinTicketEntity = new MachinTicketPoolEntity();
        machinTicketEntity.setUuid(UUIDUitl.UUID32(false));
        machinTicketEntity.setInvoiceType(BeanSelfUtils.convertInvoiceType(invoiceData.getStr("invoice_type")));
        machinTicketEntity.setConsumeKind(invoiceData.getStr("kind"));
        machinTicketEntity.setInvoiceCode(invoiceCode);
        machinTicketEntity.setInvoiceNo(invoiceNo);
        machinTicketEntity.setPurchaserName(invoiceData.getStr("buyer_name"));
        machinTicketEntity.setPurchaserTaxNo(invoiceData.getStr("buyer_tax_no"));
        machinTicketEntity.setSellerName(invoiceData.getStr("seller_name"));
        machinTicketEntity.setSellerTaxNo(invoiceData.getStr("seller_tax_no"));
        machinTicketEntity.setInvoiceDate(invoiceData.getStr("create_date"));
        machinTicketEntity.setPrintedMark(invoiceData.getStr("printed_mark"));
        machinTicketEntity.setAmountBig(invoiceData.getStr("amount_big"));
        machinTicketEntity.setAmountSmall(invoiceData.getStr("amount_small"));
//        machinTicketEntity.setImageId(imageId);
        machinTicketEntity.setCollector(UserInfoUtil.getUserNickName());
        machinTicketEntity.setCollectorId(UserInfoUtil.getUserID());
        machinTicketEntity.setPersonLiable(UserInfoUtil.getUserNickName());
        machinTicketEntity.setPersonLiableId(UserInfoUtil.getUserID());
        machinTicketEntity.setReimbursementStatus(CodeConstant.REIMBURSEMENT_1);
//        machinTicketEntity.setProcedureStatus(CodeConstant.APPROVAL_1);
        machinTicketEntity.setCreateTimeStr(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        if (machinTicket != null) {
//            minIOUtils.removeObject(BUCKET_NAME, GROUP_INVOICE, machinTicket.getImageId());
//            machinTicketPoolMapper.deleteById(machinTicket.getUuid());
//            machinTicketPoolMapper.insert(machinTicketEntity);
            return Response.error("PUR_102");
        } else {
            machinTicketPoolMapper.insert(machinTicketEntity);
        }
        return Response.success();
    }

    //客运汽车票解析入库【10505】
    private Response dealBusTicket(cn.hutool.json.JSONObject invoiceData) {
        ////用发票代码+号码确定唯一
        String invoiceCode = invoiceData.getStr("invoice_code1");
        String invoiceNo = invoiceData.getStr("invoice_no1");
        QueryWrapper<BusTicketPoolEntity> busQuery = new QueryWrapper<>();
        busQuery.eq("invoice_code", invoiceCode);
        busQuery.eq("invoice_no", invoiceNo);
        BusTicketPoolEntity busTicket = busTicketPoolMapper.selectOne(busQuery);
        BusTicketPoolEntity busTicketEntity = new BusTicketPoolEntity();
        busTicketEntity.setUuid(UUIDUitl.UUID32(false));
        busTicketEntity.setInvoiceType(BeanSelfUtils.convertInvoiceType(invoiceData.getStr("invoice_type")));
        busTicketEntity.setConsumeKind(invoiceData.getStr("kind"));
        busTicketEntity.setInvoiceCode(invoiceCode);
        busTicketEntity.setInvoiceNo(invoiceNo);
        String travelDate = invoiceData.getStr("create_date");
        if (StrUtil.isNotBlank(travelDate)) {
            busTicketEntity.setTravelDate(BeanSelfUtils.removerStr(travelDate));
        }
        busTicketEntity.setTravelTime(invoiceData.getStr("time"));
        busTicketEntity.setTravelName(invoiceData.getStr("name"));
        busTicketEntity.setFromStation(invoiceData.getStr("station_geton"));
        busTicketEntity.setArriveStation(invoiceData.getStr("station_getoff"));
        busTicketEntity.setAmountBig(invoiceData.getStr("amount_big"));
        busTicketEntity.setAmountSmall(invoiceData.getStr("amount_small"));
//        busTicketEntity.setImageId(imageId);
        busTicketEntity.setCollector(UserInfoUtil.getUserNickName());
        busTicketEntity.setCollectorId(UserInfoUtil.getUserID());
        busTicketEntity.setPersonLiable(UserInfoUtil.getUserNickName());
        busTicketEntity.setPersonLiableId(UserInfoUtil.getUserID());
        busTicketEntity.setReimbursementStatus(CodeConstant.REIMBURSEMENT_1);
//        busTicketEntity.setProcedureStatus(CodeConstant.APPROVAL_1);
        busTicketEntity.setCreateTimeStr(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        if (busTicket != null) {
//            minIOUtils.removeObject(BUCKET_NAME, GROUP_INVOICE, busTicket.getImageId());
//            busTicketPoolMapper.deleteById(busTicket.getUuid());
//            busTicketPoolMapper.insert(busTicketEntity);
            return Response.error("PUR_102");
        } else {
            busTicketPoolMapper.insert(busTicketEntity);
        }
        return Response.success();
    }

    /**
     * 根据人员查询未报账的发票数据
     *
     * @param dto
     * @return
     */
    public Response invoiceCollectionQuery(InterfaceInvoiceDTO dto) {
        Response<String> info = managerClientService.info(dto.getUserCode());
        List<InvoiceCollectionEntity> invoiceCollectionEntities=null;
        if(CodeConstant.T0000.equals(info.getCode())){
            QueryWrapper<InvoiceCollectionEntity> invoiceQuery = new QueryWrapper<>();
            invoiceQuery.in("reimbursement_status", CodeConstant.NOT_REIMBURSEMENT).eq("collector_id", info.getData());
            if (StrUtil.isNotBlank(dto.getCreateTimeStart())) {
                //invoiceQuery.ge("create_time_str", dto.getCreateTimeStart() + timeStart);
                invoiceQuery.apply("UNIX_TIMESTAMP(create_time) >= UNIX_TIMESTAMP('" +dto.getCreateTimeStart() + timeStart  + "')");
            }
            if(StrUtil.isNotBlank(dto.getCreateTimeEnd())){
                //invoiceQuery.ge("create_time_str", dto.getCreateTimeEnd() + timeEnd);
                invoiceQuery.apply("UNIX_TIMESTAMP(create_time) <= UNIX_TIMESTAMP('" +dto.getCreateTimeEnd() + timeEnd  + "')");
            }
            invoiceQuery.orderByDesc("create_time");
            invoiceCollectionEntities = baseMapper.selectList(invoiceQuery);
        }
        return Response.success(invoiceCollectionEntities);
    }
}
